<template>
    <div>
        <n-tabs v-model:value="tabValue" justify-content="start" type="line">
            <n-tab-pane name="list" tab="文章列表">
                <div v-for="(blog, index) in blogList" :key="index" style="margin-bottom:15px">
                    <n-card :title="blog.title">
                        {{ blog.content }}

                        <template #footer>
                            <n-space align="center">
                                <div>发布时间：{{ blog.create_time }}</div>
                                <n-button type="info" @click="toUpdate(blog)">修改</n-button>
                                <n-button type="error" @click="toDelete(blog)">删除</n-button>

                            </n-space>
                        </template>
                    </n-card>
                </div>
                <n-space>
                    <n-pagination v-model:page="pageInfo.page" v-model:page-size="pageInfo.pageSize"
                        :page-count="pageInfo.pageCount" :on-update:page="updatePage" show-size-picker
                        :page-sizes="pageSizes" :on-update:page-size="updatePageSize" />
                </n-space>
            </n-tab-pane>
            <n-tab-pane name="add" tab="添加文章">
                <n-form>
                    <n-form-item label="标题">
                        <n-input v-model:value="addArticle.title" placeholder="请输入标题" />
                    </n-form-item>
                    <n-form-item label="分类">
                        <n-select v-model:value="addArticle.categoryId" :options="categoryOptions"
                            placeholder="请选择分类" />
                    </n-form-item>
                    <n-form-item label="内容">
                        <RichTextEditor v-model="addArticle.content" ref="richTextEditor" />
                        <!-- 
                            v-model使用在一个组件上时，v-model 会被展开为如下的形式：
                            <CustomInput
                            :modelValue="searchText"
                            @update:modelValue="newValue => searchText = newValue"
                            />
                         -->
                    </n-form-item>
                    <n-form-item label="">
                        <n-button @click="add" type="info">提交</n-button>
                    </n-form-item>
                </n-form>
            </n-tab-pane>
            <n-tab-pane name="update" tab="修改文章" :disabled="true">
                <n-form>
                    <n-form-item label="标题">
                        <n-input v-model:value="updateArticle.title" placeholder="请输入标题" />
                    </n-form-item>
                    <n-form-item label="分类">
                        <n-select v-model:value="updateArticle.categoryId" :options="categoryOptions"
                            placeholder="请选择分类" />
                    </n-form-item>
                    <n-form-item label="内容">
                        <RichTextEditor v-model="updateArticle.content" ref="richTextEditor" />
                    </n-form-item>
                    <n-form-item label="">
                        <n-space>
                            <n-button @click="update" type="info">提交</n-button>
                            <n-button @click="cancleUpdate" type="warning">取消</n-button>
                        </n-space>
                    </n-form-item>
                </n-form>
            </n-tab-pane>
        </n-tabs>
    </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted } from "vue"
import { AdminStore } from "../../store/AdminStore"
import { useRouter, useRoute } from "vue-router";
import RichTextEditor from "../../components/RichTextEditor.vue"
const router = useRouter()
const route = useRoute()
const axios = inject("axios")
const message = inject("message")
const dialog = inject("dialog")
const adminStore = AdminStore()

onMounted(() => {
    getCategorys()
    getBlogs()
})
const tabValue = ref("list")
// 定义富文本编辑器组件的ref
const richTextEditor = ref(null)
// 选择框的数据
const categoryOptions = ref([])
const blogList = ref([])
// 新增文章的数据
const addArticle = reactive({
    categoryId: null,
    title: "",
    content: "",
})
//修改文章的数据
const updateArticle = reactive({
    id: null,
    categoryId: null,
    title: "",
    content: "",
})
const pageInfo = reactive({
    page: 1,
    pageSize: 3,
    pageCount: 0,
    count: 0
})

const pageSizes = [
    {
        label: '3 每页',
        value: 3
    },
    {
        label: '5 每页',
        value: 5
    },
    {
        label: '10 每页',
        value: 10
    },
]


// 页码更改
const updatePage = (page) => {
    pageInfo.page = page
    getBlogs()
}
//page-size更改
const updatePageSize = (pageSize) => {
    pageInfo.pageSize = pageSize
    getBlogs()
}


// 获取文章分类的方法
const getCategorys = async () => {
    let res = await axios.get("/category/list")
    if (res.data.code == 200) {
        res.data.rows.forEach(row => {
            categoryOptions.value.push({
                label: row.name,
                value: row.id
            })
        });
    } else if (res.data.code == 403) {
        message.error("登陆状态失效，请重新登录！")
    }
}
//获取文章列表
const getBlogs = async () => {
    let res = await axios.get(`/blog/search?page=${pageInfo.page}&pageSize=${pageInfo.pageSize}`)

    if (res.data.code == 200) {
        let tempRows = res.data.data.rows
        for (const row of tempRows) {
            row.content += " ..."
            let d = new Date(row.create_time)
            row.create_time = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}`
        }
        blogList.value = tempRows
        //文章总数
        pageInfo.count = res.data.data.count
        //    计算页码总数
        pageInfo.pageCount = parseInt(pageInfo.count / pageInfo.pageSize) + (pageInfo.count % pageInfo.pageSize > 0 ? 1 : 0)
    }
}

// 提交文章
const add = async () => {
    if (addArticle.title.trim() == "") {
        message.error("标题不能为空！")
        return
    }
    if (addArticle.categoryId == null) {
        message.error("请选择分类")
        return
    }
    if (addArticle.content == "<p><br></p>") {
        message.error("请填写文章内容")
        return
    }
    let res = await axios.post("/blog/_token/add", addArticle)
    if (res.data.code == 200) {
        message.success("添加成功")
        //将富文本编辑器内容置空
        clearRichEditor(addArticle)
        // addArticle.categoryId = null,
        //     // 因为富文本编辑器组件中有单独的htmlValue，用来保存文章内容，所以要更改组件内部的数据
        //     richTextEditor.value.clearContent()
        // addArticle.content = "<p><br></p>",
        //     addArticle.title = ""
    } else {
        message.error("添加失败")
    }
}

//修改文章按钮
const toUpdate = async (blog) => {
    tabValue.value = "update"
    let res = await axios.get(`/blog/detail?id=${blog.id}`)
    if (res.data.code == 200) {
        updateArticle.id = blog.id
        updateArticle.title = res.data.rows[0].title
        updateArticle.content = res.data.rows[0].content
        updateArticle.categoryId = res.data.rows[0].category_id
    }
}

//删除文章按钮
const toDelete = async (blog) => {
    dialog.warning({
        title: "警告",
        content: "确定删除吗",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: async () => {
            let res = await axios.delete(`/blog/_token/delete?id=${blog.id}`)
            if (res.data.code == 200) {
                message.success("删除成功")
                getBlogs()
            } else {
                message.error("删除失败")
                console.log(res.data.msg);
            }
        },

    });
}

//修改文章后提交
const update = async () => {
    if (updateArticle.title.trim() == "") {
        message.error("标题不能为空！")
        return
    }
    if (updateArticle.categoryId == null) {
        message.error("请选择分类")
        return
    }
    if (updateArticle.content == "<p><br></p>") {
        message.error("请填写文章内容")
        return
    }
    let res = await axios.put("/blog/_token/update", updateArticle)
    if (res.data.code == 200) {
        message.success("修改成功")
        //将富文本编辑器内容置空
        clearRichEditor(updateArticle)
        //重新读取博客数据
        getBlogs()
        //完成后回到list页面
        tabValue.value = "list"

    } else {
        message.error("修改失败")
    }
}
//取消修改
const cancleUpdate = () => {
    clearRichEditor(updateArticle)
    tabValue.value = "list"
}


//清除富文本编辑器
const clearRichEditor = (editor) => {
    editor.categoryId = null,
    // 因为富文本编辑器组件中有单独的htmlValue，用来保存文章内容，所以要更改组件内部的数据
    richTextEditor.value.clearContent()
    editor.content = "<p><br></p>",
    editor.title = ""
}


</script>

<style lang="scss" scoped>
</style>